/*
 * Copyright 2014 OGIS-RI All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.co.ogis_ri.optaplanner.vehiclerouting.domain.solver;

import jp.co.ogis_ri.optaplanner.vehiclerouting.domain.Vehicle;
import jp.co.ogis_ri.optaplanner.vehiclerouting.domain.core.ChainedTimeWindowedStep;
import jp.co.ogis_ri.optaplanner.vehiclerouting.domain.core.TimeWindowedStep;

import org.optaplanner.core.impl.domain.variable.listener.VariableListener;
import org.optaplanner.core.impl.score.director.ScoreDirector;

public class VehicleUpdatingVariableListener implements
		VariableListener<ChainedTimeWindowedStep> {

	@Override
	public void beforeEntityAdded(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep cargo) {
		// Do nothing
	}

	@Override
	public void afterEntityAdded(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep cargo) {
		this.updateVehicle(scoreDirector, cargo);
	}

	@Override
	public void beforeVariableChanged(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep cargo) {
		// Do nothing
	}

	@Override
	public void afterVariableChanged(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep cargo) {
		this.updateVehicle(scoreDirector, cargo);
	}

	@Override
	public void beforeEntityRemoved(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep cargo) {
		// Do nothing
	}

	@Override
	public void afterEntityRemoved(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep cargo) {
		// Do nothing
	}

	protected void updateVehicle(final ScoreDirector scoreDirector,
			final ChainedTimeWindowedStep sourceCargo) {
		TimeWindowedStep previousStep = sourceCargo.getPreviousStep();
		Vehicle vehicle = previousStep == null ? null : previousStep
				.getVehicle();
		ChainedTimeWindowedStep shadowCargo = sourceCargo;
		while (shadowCargo != null && shadowCargo.getVehicle() != vehicle) {
			scoreDirector.beforeVariableChanged(shadowCargo, "vehicle");
			shadowCargo.setVehicle(vehicle);
			scoreDirector.afterVariableChanged(shadowCargo, "vehicle");
			shadowCargo = shadowCargo.getNextStep();
		}
	}

}
